package com.gxgeek.javabasic.java8;

import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @author gaoxing
 * @create 2017-09-29 上午11:22
 */
public class Collect {
    @Test
    public void tets1(){
        final Integer[] integers = Lists.newArrayList(1, 2, 3, 4, 5)
                .stream()
                .collect(() -> new Integer[]{0}, (a, x) -> a[0] += x, (a1, a2) -> a1[0] += a2[0]);
        System.out.println(Arrays.stream(integers).collect(toList()));
    }
    @Test
    public void tets2(){
        ArrayList<Person> list = Lists.<Person>newArrayList();
        list.add(Person.builder().name("gx").type(1).build());
        list.add(Person.builder().name("wx").type(2).build());
        HashMap<Integer,List<Person>> map = list.stream()
                .collect(() -> new HashMap<Integer,List<Person>>(),
                        (h, x) -> {
                            List<Person> value = h.getOrDefault(x.getType(), Lists.newArrayList());
                            value.add(x);
                            h.put(x.getType(), value);
                        },
                        (m1,m2)->m1.putAll(m2)
//                        HashMap::putAll
                );
        System.out.println(map);
    }

    @Test
    public void tets3(){
        ArrayList<Person> list = Lists.<Person>newArrayList();
        list.add(Person.builder().name("gx").type(1).build());
        list.add(Person.builder().name("wx").type(2).build());

        Lists.<Person>newArrayList().stream()
                .collect(() -> new HashMap<Integer,List<Person>>(),
                        (h, x) -> {
                            List<Person> value = h.getOrDefault(x.getType(), Lists.newArrayList());
                            value.add(x);
                            h.put(x.getType(), value);
                        },
                        HashMap::putAll
                );
//groupBy形式
        HashMap<Integer,List<Person>> map = list.stream()
                .collect(Collectors.groupingBy(Person::getType, HashMap::new, Collectors.toList()));
//因为对值有了操作,因此我可以更加灵活的对值进行转换
        System.out.println(map);
        HashMap<Integer,Set<String>> map1  = list.stream()
                .collect(Collectors.groupingBy(Person::getType, HashMap::new, Collectors.mapping(Person::getName,Collectors.toSet())));
        System.out.println(map1);
    }

}

@Data
@AllArgsConstructor
@Builder
class Person{
    String name;
    Integer type;

}
